<template>
  <view class="chat-container">
    <scroll-view class="chat-box" scroll-y="true" :scroll-into-view="scrollIntoView" :style="{ paddingTop: `${statusBarHeight}px` }">
      <view v-for="(message, index) in messages" :key="index" :class="{'message': true, 'message-right': message.isMe}">
        <!-- AI消息 -->
        <template v-if="!message.isMe">
          <view class="message-left">
            <image :src="message.avatar" class="avatar"></image>
            <view class="bubble" :class="{'typing': isStreaming && streamingIndex === index}">
              {{ message.text }}
            </view>
          </view>
        </template>
        <!-- 用户消息 -->
        <template v-else>
          <view class="message-right">
            <view class="bubble user-bubble"><p v-html="message.text"></p></view>
            <image 
              :src="userAvatar || '/static/images/default-avatar.png'" 
              class="avatar"
            ></image>
          </view>
        </template>
        <text class="timestamp">{{ message.timestamp }}</text>
      </view>
    </scroll-view>
    <view class="input-box">
      <input type="text" v-model="inputMessage" placeholder="输入消息..." @confirm="sendMessage" />
      <view class="btn-group">
        <button class="action-btn send-btn" @click="sendMessage">
          <uni-icons type="paperplane-filled" size="20" color="#FFFFFF"></uni-icons>
        </button>
        <button class="action-btn clear-btn" @click="clearInput">
          <uni-icons type="closeempty" size="20" color="#666666"></uni-icons>
        </button>
      </view>
    </view>
  </view>
</template>

<script>
  import {queryChat} from "../../api/chat";
  export default {
    data() {
      return {
        statusBarHeight: 0,
        inputMessage: '',
        scrollIntoView: '',
        userAvatar: '',
        messages: [
          {
            text: '你好！欢迎开始聊天。',
            timestamp: '刚刚',
            isMe: false,
            avatar:'https://s.coze.cn/t/CouNLdnJW5YEI00I/'
          }
        ],
        streamingIndex: -1,  // 用于追踪正在流式输出的消息
        isStreaming: false   // 是否正在流式输出
      }
    },
    created() {
      // 获取状态栏高度
      const systemInfo = uni.getSystemInfoSync()
      this.statusBarHeight = systemInfo.statusBarHeight
      // 获取用户头像
      this.getUserAvatar()
    },
    methods: {
      // 获取用户头像方法
      getUserAvatar() {
        try {
          const userStr = uni.getStorageSync('user')
          console.log('获取到的原始用户信息：', userStr)
          
          // 将字符串转换为对象
          const userInfo = userStr ? JSON.parse(userStr) : null
          console.log('转换后的用户信息：', userInfo)
          
          if (userInfo && userInfo.avatar) {
            this.userAvatar = userInfo.avatar
          } else {
            // 如果没有头像，设置默认头像
            this.userAvatar = '/static/images/default-avatar.png'
          }
          console.log('最终设置的头像地址：', this.userAvatar)
        } catch (e) {
          console.error('获取用户头像失败:', e)
          // 发生错误时也设置默认头像
          this.userAvatar = '/static/images/default-avatar.png'
        }
      },
      formatCurrentTime() {
        const now = new Date();
        const hours = String(now.getHours()).padStart(2, '0');
        const minutes = String(now.getMinutes()).padStart(2, '0');
        return `${hours}:${minutes}`;
      },
      // 流式输出文本
      async streamText(text, messageIndex) {
        this.isStreaming = true
        this.streamingIndex = messageIndex
        const delay = 50  // 每个字符的延迟时间（毫秒）
        
        for (let i = 0; i < text.length; i++) {
          this.messages[messageIndex].text = text.substring(0, i + 1)
          await new Promise(resolve => setTimeout(resolve, delay))
        }
        
        this.isStreaming = false
        this.streamingIndex = -1
      },
      sendMessage() {
        if (this.inputMessage.trim()) {
          // 添加用户消息
          this.messages.push({
            text: this.inputMessage,
            timestamp: this.formatCurrentTime(),
            isMe: true,
            avatar: this.userAvatar
          });

          // 添加一个空的AI消息占位
          const aiMessageIndex = this.messages.length
          this.messages.push({
            text: '',
            timestamp: this.formatCurrentTime(),
            isMe: false,
            avatar: 'https://s.coze.cn/t/CouNLdnJW5YEI00I/',
          })

          // 发送API请求
          queryChat({content:this.inputMessage}).then(res => {
            // 开始流式输出
            this.streamText(res.data.data, aiMessageIndex)
          })
          
          this.inputMessage = '';
        }
      },
      clearInput() {
        this.inputMessage = '';
      }
    }	
  }
</script>
<style>
.chat-container {
  display: flex;
  flex-direction: column;
  height: 100vh;
  background-color: #f9f9f9;
  padding-bottom: 180rpx; /* 增加底部间距 */
}

.chat-box {
  flex: 1;
  overflow-y: auto;
  padding: 10px;
  background-color: #f9f9f9;
  height: calc(100vh - 180rpx); /* 调整高度计算 */
  padding-bottom: 20rpx;
}

.message {
  margin-bottom: 15px;
  display: flex;
  flex-direction: column;
  width: 100%;
}

.message-left {
  display: flex;
  flex-direction: row;
  align-items: flex-start;
  padding-right: 20%;
}

.message-right {
  display: flex;
  flex-direction: row;
  justify-content: flex-end;
  align-items: flex-start;
  width: 100%;
}

.message-right .bubble {
  margin-right: 10px;
}

.message-right .avatar {
  margin: 0;
}

.message-left .avatar {
  margin-right: 10px;
}

.bubble {
  max-width: 70%;
  padding: 10px 15px;
  border-radius: 10px;
  background-color: #fff;
  box-shadow: 0 1px 2px rgba(0,0,0,0.1);
  word-wrap: break-word;
  color: #333;
}

.user-bubble {
  background-color: #03a9f4;
  color: #fff;
}

.avatar {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  margin: 0 10px;
  flex-shrink: 0;
  display: block;
  object-fit: cover;
}

.timestamp {
  font-size: 12px;
  color: #999;
  margin-top: 5px;
  text-align: right;
}

.input-box {
  display: flex;
  align-items: center;
  padding: 10px;
  background-color: #f9f9f9;
  border-top: 1px solid #eee;
  height: 100rpx;
  box-sizing: border-box;
  position: fixed;
  bottom: 140rpx; /* 调整输入框位置，往上移 */
  left: 0;
  right: 0;
  padding-bottom: calc(10px + env(safe-area-inset-bottom));
  z-index: 100;
}

.input-box input {
  flex: 1;
  height: 40px;
  padding: 0 15px;
  border-radius: 20px;
  border: 1px solid #eee;
  font-size: 16px;
  background-color: #fff;
  margin-right: 10px;
}

.btn-group {
  display: flex;
  gap: 8px;
}

.action-btn {
  width: 40px;
  height: 40px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  border: none;
  cursor: pointer;
  transition: all 0.3s ease;
}

.send-btn {
  background-color: #03a9f4;
}

.clear-btn {
  background-color: #fff;
}

.action-btn:active {
  transform: scale(0.95);
}

.message-left .bubble {
  position: relative;
}

/* 添加打字机光标效果 */
.message-left .bubble::after {
  content: '|';
  position: absolute;
  right: -2px;
  animation: cursor 0.8s infinite;
  display: none;
}

.message-left .bubble.typing::after {
  display: inline;
}

@keyframes cursor {
  0%, 100% { opacity: 1; }
  50% { opacity: 0; }
}
</style>